<template>
	<view class="login-container">
		<uni-icons type="contact-filled" size="100" color="#afafaf"></uni-icons>
		<button
			@getuserinfo="getUserInfo" open-type="getUserInfo"
			type="primary" class="login-btn">一键登录</button>
		<text class="login-tip">登录后尽享更多权益</text>
	</view>
</template>

<script>
	import { mapState,mapMutations } from 'vuex'
	export default {
		methods: {
			...mapMutations('user',['updateToken','updateUserInfo']),
			getToken(userInfoObj){				// 获取 token 值
				uni.login({
					success: async (res) => {
						// 校验是否登录失败
						if(res.errMsg !== 'login:ok'){
							return uni.$showMsg('登录失败')
						}
						
						// 通过 res.code 换取 token 值
						const queryObj = {
							code: res.code,
							encryptedData: userInfoObj.encryptedData,
							iv: userInfoObj.iv,
							rawData: userInfoObj.rawData,
							signature: userInfoObj.signature
						}
						console.log(queryObj)
						// 发送请求，获取数据
						const { data: loginRes } = await uni.$http.post('/api/public/v1/users/wxlogin',queryObj)
						console.log(loginRes)
						if(loginRes.meta.status !== 200){
							return uni.$showMsg('登录失败')
						}
						// 将 token 值存储到 vuex 当中
						this.updateToken(loginRes.message.token)
						
						// 校验是否是强制被登录
						if(redirect){
							if(redirect.openType === 'switchTab'){
								uni.switchTab({
									url: redirect.from
								})
							}else {
								uni.navigateBack({
									url: redirect.from
								})
							}
						}
					},
					fail: (err) => {
						// 当有错误时，直接提示登录失败
						if(err){
							return uni.$showMsg('登录失败')
						}
					}
				})
			},
			getUserInfo(e){		// 获取用户信息
				// 校验用户是否取消登录授权
				if(e.detail.errMsg === 'getUserInfo:fail auth deny'){
					return uni.$showMsg('您取消登录授权')
				}
				// 将用户信息存储到 vuex 当中
				this.updateUserInfo(e.detail.userInfo)
				// 获取 token 值
				this.getToken(e.detail)
			}
		},
		computed: {
			...mapState('user',['redirect','userInfo'])
		},
		name:"my-login"
	}
</script>

<style lang="scss">
.login-container {
	height: 750rpx;
	background-color: #f8f8f8;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	position: relative;
	overflow: hidden;
	
	&::after {
		content: ' ';
		display: block;
		width: 100%;
		height: 40px;
		background-color: #fff;
		position: absolute;
		bottom: 0;
		left: 0;
		border-radius: 100%;
		transform: translateY(50%);
	}
	
	.login-btn {
		width: 90%;
		border-radius: 100px;
		margin: 15px 0;
		background-color: #C00000;
	}
	
	.login-tip {
		font-size: 12px;
		color: gray;
	}
}
</style>